package offer.roratearray;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author Elephas
 * @Date 2022/1/23
 **/
public class GenerateParenthesis {
    public static void main(String[] args) {
        int TEST = 4;
        List<String> l1 = new GenerateParenthesis().generateParenthesis(TEST);
        List<String> l2 = new GenerateParenthesis().generateParenthesisBackTrack(TEST);
        Set<String> s1 = l1.stream().collect(Collectors.toSet());
        Set<String> miss = l2.stream().collect(Collectors.toSet());
        s1.stream().forEach((s)->{
            miss.remove(s);
        });
        miss.stream().forEach(System.out::println);
    }
    public List<String> generateParenthesis(int n){
        Set<String> stringSet = new HashSet<>();
        stringSet.add("()");
        return generateParenthesisIterator(n,stringSet).stream().collect(Collectors.toList());
    }

    public Set<String> generateParenthesisIterator(int iter,Set<String> stringSet){
        if(iter == 1) {
            return stringSet;
        }
        Set<String> newStringSet = new HashSet<>();
        stringSet.stream().forEach((s)->{
            newStringSet.add("()"+s);
            newStringSet.add("("+s+")");
            newStringSet.add(s+"()");
        });
        return generateParenthesisIterator(iter -1,newStringSet);
    }

    /*
        官方解析：回溯法
     */
    public List<String> generateParenthesisBackTrack(int n) {
        List<String> ans = new ArrayList<String>();
        backtrack(ans, new StringBuilder(), 0, 0, n);
        return ans;
    }

    public void backtrack(List<String> ans, StringBuilder cur, int open, int close, int max) {
        if (cur.length() == max * 2) {
            ans.add(cur.toString());
            return;
        }
        if (open < max) {
            cur.append('(');
            backtrack(ans, cur, open + 1, close, max);
            cur.deleteCharAt(cur.length() - 1);
        }
        if (close < open) {
            cur.append(')');
            backtrack(ans, cur, open, close + 1, max);
            cur.deleteCharAt(cur.length() - 1);
        }
    }

}
